package org.lanqiao.userprofile.movie.common;

import com.alibaba.fastjson.JSONObject;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import java.io.IOException;

public class TextToImg {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final String API_KEY = "9ab21d2b1878613137b9ea44b4d02328f23855a405f332670a38d2ea27047a88";
    public static final String URL = "https://api.tigerbot.com/v1/text2image";

    public static String getImg(String text) throws InterruptedException, IOException {
        if (text.equals("female")) {
            text = "女生";
        } else if (text.equals("male")) {
            text = "男生";
        }
        OkHttpClient client = new OkHttpClient();

        JSONObject payload = new JSONObject();
        payload.put("text", "一个" + text + "头像");
        payload.put("modifiers", new String[]{"油画", "哑光"});
        payload.put("width", 768);
        payload.put("height", 768);
        payload.put("n_iter", 1);
        payload.put("seed", 0);

        RequestBody body = RequestBody.create(JSON, payload.toString());

        Request request = new Request.Builder()
                .url(URL)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .post(body)
                .build();

        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        JSONObject result = JSONObject.parseObject(responseBody);
        System.out.println(result.getString("id"));


        String yourTaskId = result.getString("id");
        String url = "https://api.tigerbot.com/v1/text2image/" + yourTaskId;

        request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", "Bearer " + API_KEY)
                .get()
                .build();

        response = client.newCall(request).execute();
        responseBody = response.body().string();
        result = JSONObject.parseObject(responseBody);
        while (!result.getString("status").equals("已成功")) {
            Thread.sleep(1000);
            response = client.newCall(request).execute();
            responseBody = response.body().string();
            result = JSONObject.parseObject(responseBody);
            //System.out.println(result.getString("status"));
        }
        System.out.println(responseBody);
        return result.getString("output_image");
    }
}
